package com.bite.springmvc.controller;

import com.bite.springmvc.model.UserInfo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/response")
//@RestController
@Controller
//如果向返回一个前端页面（这里的注解必须是@Controller）返回的是视图
public class ResponseController {
    @RequestMapping("/index")
    public String index(){
        //如果不加斜杠 访问的路径是 /response/index.html
        //如果加斜杠 访问的路径是  /index.html （绝对路径）
        //统一思想 全部加斜杠
        //访问 URL路径：http://127.0.0.1:8080/response/index
        return "/index.html";
    }

    //返回数据
    @ResponseBody
    @RequestMapping("/returnData")
    public String returnData(){
        return "返回数据";
    }

    //这里想返回数据
    //但是通过抓包发现，返回的类型是 html
    //这里的代码通过浏览器进行解析了
    @ResponseBody
    @RequestMapping("/returnHTML")
    public String returnHTML(){
        return "<h1>我是HTML页面</h1>";
    }


    //返回JSON 这里一定是返回的是收据
    //依然用@ResponseBody
    //当我们返回的是对象是 spring会自动的把他转换为 application/json
    @ResponseBody
    @RequestMapping("/returnJson")
    public UserInfo returnJson(){
        UserInfo userInfo = new UserInfo("zhangsan","123456",18);
        return userInfo;
    }

    //设置状态码
    @ResponseBody
    @RequestMapping("/setStatus")
    public String setStatus(HttpServletResponse response){
        response.setStatus(401);
        return "设置状态码成功";
    }

    //json方式输出
    @ResponseBody
    @RequestMapping(value = "/r1",produces = "application/json;charset = UTF-8")
    public String r1(){
        return "{\"status\":400}";
    }

    @ResponseBody
    @RequestMapping("/setheader")
    public String setheader(HttpServletResponse response){
        response.setHeader("MyHeader","MyHeaderValue");
        return "hahaha";
    }
}
